package main

import "fmt"

/**
模拟路径
*/

func spiralOrder(matrix [][]int) []int {
	if matrix == nil || len(matrix) == 0 || matrix[0] == nil || len(matrix[0]) == 0 {
		return []int{}
	}

	directions := [4][6]int{
		// 横向(col)  纵向(row) 横向边界(low,high) 纵向边界(low,high)
		{1, 0, 0, 0, 1, 0},
		{0, 1, 0, -1, 0, 0},
		{-1, 0, 0, 0, 0, -1},
		{0, -1, 1, 0, 0, 0},
	}
	rowLimits := [2]int{0, len(matrix) - 1}
	celLimits := [2]int{0, len(matrix[0]) - 1}

	res := []int{}

	directionIndex := 0

	row, col := 0, 0
	for i := 0; i < len(matrix)*len(matrix[0]); i++ {
		res = append(res, matrix[row][col])

		// 移动
		nextRow, nextCol := row+directions[directionIndex][1], col+directions[directionIndex][0]

		// 判断越界
		if nextRow < rowLimits[0] || nextCol < celLimits[0] || nextRow > rowLimits[1] || nextCol > celLimits[1] {
			// 调整新边界值
			celLimits[0] += directions[directionIndex][2]
			celLimits[1] += directions[directionIndex][3]

			rowLimits[0] += directions[directionIndex][4]
			rowLimits[1] += directions[directionIndex][5]

			// 调转方向
			directionIndex = (directionIndex + 1) % 4
			nextRow, nextCol = row+directions[directionIndex][1], col+directions[directionIndex][0]
		}
		row, col = nextRow, nextCol
	}
	return res
}

func main() {
	nums := spiralOrder([][]int{
		{1, 2, 3},
		{4, 5, 6},
		{7, 8, 9},
	})
	fmt.Println(nums)
}
